package com.wandian.util;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

/**
 * @author long
 * @Create 2012-10-6 上午11:34:47
 * @QQ 108232706
 * @version 1.0
 * @description ProtoBufUtil
 */
public class ProtoBufUtil {
	private static ProtoBufUtil instance = null;
	private final Charset charset = Charset.forName("UTF-8");

	public static ProtoBufUtil getInstance() {
		if (instance == null) {
			syncInit();
		}
		return instance;
	}

	private static synchronized void syncInit() {
		if (instance == null) {
			instance = new ProtoBufUtil();
		}
	}

	public void printByteBuffer(String msg, int position, int length,
			ByteBuffer contentBuffer) {
		// 转成16进制字符串
		int oldposition = contentBuffer.position();
		contentBuffer.position(position);
		String hs = "";
		String tmp = "";
		for (int n = 0; n < length; n++) {
			// 整数转成十六进制表示
			tmp = (java.lang.Integer.toHexString(contentBuffer.get() & 0XFF));
			if (tmp.length() == 1) {
				hs = hs + "0" + tmp + ",";
			} else {
				hs = hs + tmp + ",";
			}
		}
		contentBuffer.position(oldposition);// 恢复起初位置
		tmp = null;
		hs.toUpperCase();// 转成大写
		String result = msg + " length:" + length + " content:" + hs;
		Log.debug(result);
	}

	public String decode(ByteBuffer buffer) {
		return decode(buffer, true);
	}

	public String decode(ByteBuffer buffer, boolean ischarset)
	{ // 解码
		if (ischarset) {
			CharBuffer charBuffer = charset.decode(buffer);
			return charBuffer.toString();
		} else {
			byte[] bytes = new byte[buffer.remaining()];
			buffer.get(bytes, 0, buffer.remaining());
			try {
				return new String(bytes, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				return "";
			}
		}

	}

	public ByteBuffer encode(String str) {
		return encode(str, true);
	}

	public ByteBuffer encode(String str, boolean ischarset)
	{ // 编码
		if (ischarset) {
			return charset.encode(str);
		} else {
			byte[] bytes;
			ByteBuffer temBuffer = null;
			try {
				bytes = str.getBytes("utf-8");
				temBuffer = ByteBuffer.allocate(bytes.length);
				temBuffer.put(bytes);
			} catch (UnsupportedEncodingException e) {
			}

			return temBuffer;
		}

	}

}
